package xyz.scootaloo.draft

import cn.hutool.core.lang.Console
import org.junit.Test

/**
 * @author flutterdash@qq.com
 * @since 2021/4/27 22:37
 */
class Case9 {

    private fun func(input: Int): Int {
        var preSum = 1
        var curSum = 1
        var side = 1
        val cache = HashMap<Int, Int>()

        for (n in 2 until input/2) {
            curSum = dp(n, cache)
            if (preSum <= input) {
                if (curSum > input || diff(preSum, input) < diff(curSum, input)) {
                    curSum = preSum
                    side = n
                    break
                }
            }
            preSum = curSum
        }

        printPrismatic(side - 1)
        return input - curSum
    }

    private fun dp(n: Int, cache: HashMap<Int, Int>): Int {
        if (n == 1)
            return 1
        var cacheValue = cache[n]
        return if (cacheValue != null) {
            cacheValue
        } else {
            cacheValue =  dp(n - 1, cache) + ((n - 1) * 4)
            cache[n] = cacheValue
            cacheValue
        }
    }

    private fun printPrismatic(n: Int) {
        val star = '*'
        val space = ' '
        if (n == 0)
            println(star)

        for (row in 1 until (n * 2)) {
            val starCount = if (row <= n) {
                row * 2 - 1
            } else {
                (n * 2 - row) * 2 - 1
            }
            val spaceCount = n - (starCount / 2) - 1
            for (i in 1..spaceCount)
                print(space)
            for (i in 1..starCount)
                print(star)
            println()
        }
    }

    private fun diff(numa: Int, numb: Int): Int =
        numb - numa

    @Test
    fun test0() {
        Console.log(func(1))
        Console.log(func(10))
        Console.log(func(14))
    }

}
